package com.cssl.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cssl.pojo.Users;
import com.cssl.service.UsersService;
import com.cssl.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class RedisController {

    @Autowired
    private UsersService service;
    @Autowired
    private RedisUtil redisUtil;
    //@Autowired
    //private RedisTemplate<String,Users> template;

    @GetMapping("/list/{pageIndex}/{pageSize}")
    public List<Users> list(@PathVariable("pageIndex") Long pageIndex,
                            @PathVariable("pageSize") Long pageSize){

        /*List<Users> list = template.opsForList().range("list",(pageIndex-1)*pageSize,pageIndex*pageSize-1);
        //查询数据库
        if(list == null || list.size()==0){
            list = service.list(new Page<Users>(pageIndex,pageSize));
            template.opsForList().rightPushAll("list",list);
        }
        return list;*/

        List<Object> list = redisUtil.lRange("list",(pageIndex-1)*pageSize,pageIndex*pageSize-1);

        if(list != null && list.size()>0){
            List<Users> users = list.stream().map(o->(Users)o).collect(Collectors.toList());
            redisUtil.expire("list",60L);
            return users;
        }
        //查数据库
        List<Users> us = service.list(new Page<Users>(pageIndex,pageSize));
        redisUtil.rPushAll("list",us,60L);
        return us;
    }


    //============ redis 注解 =============
    @GetMapping("/findById/{id}")
    public Users findUserById(@PathVariable("id") Integer id){
        return service.getUserById(id);
    }

    @GetMapping("/saveUpdate")
    public Users saveOrUpdate(Users user){
        return service.saveUpdate(user);
    }

    @GetMapping("/removeById/{id}")
    public boolean remove(@PathVariable("id") int id){
        return service.removeUser(id);
    }

    @GetMapping("/find")
    public List<Users> find(){
        return service.findAll();
    }

}
